package com.cheyun.netsalev3.viewmodel

import android.content.Intent
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.bean.DialogParam
import com.cheyun.netsalev3.bean.SalesListParam
import com.cheyun.netsalev3.bean.basedata.Customerlevel
import com.cheyun.netsalev3.bean.basedata.Member
import com.cheyun.netsalev3.repository.CueTransferActivityRepository
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.MainActivity
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyDialog
import com.cheyun.netsalev3.widget.TimePickerFragment
import com.jeremyliao.liveeventbus.LiveEventBus
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class CueTransferActivityViewModel(var cueTransferActivityRepository: CueTransferActivityRepository) : BaseViewModel() {
    //移交用户
    var member = ArrayList<Member>()
    var memberName = ObservableField<String>("")
    var memberPosition = -1

    var sales = ArrayList<SalesListParam>()

    //用户级别
    var customerlevel = MySharedPreferences.getBaseData()?.customerlevel
    var customerlevelName = ObservableField<String>("")
    var customerlevelPosition = -1
    //分配类型
    var userType = ArrayList<Member>()
    var userTypeName = ObservableField<String>("分配至用户")
    var userTypePosition = 0
    var userTypeId = MutableLiveData<Int>()
    fun userTypeInit(){
        userType.add(Member("","分配至用户",0,0,0))
        userType.add(Member("","分配至经销商",1,0,0))
    }

    fun memberInit(){
        member.clear()
        var memberList = MySharedPreferences.getBaseData()?.member
        var dealerId = MySharedPreferences.getLoginData()?.member?.dealerid!!
        var check = false
        if(MySharedPreferences.getLoginData()?.channel?.isgroup.equals("1") && MySharedPreferences.getLoginData()?.member?.dealerid!=0){
            check = true
        }
        memberList?.apply {
            for (it in this) {
                if(check){
                    if(it.dealerid == dealerId){
                        member.add(it)
                    }
                }else{
                    member.add(it)
                }
            }
        }
    }

    var enableCustomerLevel:MutableList<Customerlevel> = mutableListOf()

    var time = ObservableField<String>("")
    /**
     * 移交
     */
    fun yijiao(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            if(userTypePosition == 0) {

                member?.apply {
                    var list = ArrayList<DialogParam>()
                    for (it in this) {
                        var item = DialogParam(it.realname, it.uid.toString())
                        list.add(item)
                    }
                    var diolog = MyDialog.newInstance("分配线索", list)
                    diolog.huidiaPosition = this@CueTransferActivityViewModel::myPopSetData
                    diolog.show(content.supportFragmentManager, "missiles2")
                }
            }else{
                sales?.apply {
                    var list = ArrayList<DialogParam>()
                    for (it in this) {
                        var item = DialogParam(it.abname, it.salesid)
                        list.add(item)
                    }
                    var diolog = MyDialog.newInstance("分配线索", list)
                    diolog.huidiaPosition = this@CueTransferActivityViewModel::myPopSetData
                    diolog.show(content.supportFragmentManager, "missiles2")
                }
            }
        }
    }

    /**
     * 选中移交回调
     */
    fun myPopSetData(position: Int) {
        memberPosition = position
        if (memberPosition != -1) {
            if(userTypePosition == 0) {
                memberName.set(member!![memberPosition].realname)
            }else{
                memberName.set(sales!![memberPosition].abname)
            }
        }
    }

    /**
     * 移交
     */
    fun setUserType(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            userType?.apply {
                var list = ArrayList<DialogParam>()
                for (it in this) {
                    var item = DialogParam(it.realname, it.uid.toString(),"",userTypePosition == it.uid)
                    list.add(item)
                }
                var diolog = MyDialog.newInstance("分配类型", list)
                diolog.huidiaPosition = this@CueTransferActivityViewModel::userTypePopSetData
                diolog.show(content.supportFragmentManager, "missiles2")
            }
        }
    }

    /**
     * 选中移交回调
     */
    fun userTypePopSetData(position: Int) {
        if(userTypePosition != position){
            memberName.set("")
            memberPosition = -1
        }
        userTypePosition = position
        if (userTypePosition != -1) {
            userTypeName.set(userType!![userTypePosition].realname)
        }
        if(userTypePosition == 1 && sales.size == 0){
            cueTransferActivityRepository.getSales(this::setSalesData);
        }
        if(userTypePosition == 0){
            //member = MySharedPreferences.getBaseData()?.member
            memberInit()
        }
        userTypeId.postValue(userTypePosition)
    }

    private fun setSalesData(item: List<SalesListParam>) {
        for (i in item) {
            sales.add(i)
        }
    }

    /**
     * 选择级别
     */
    fun level(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            customerlevel?.apply {
                var list = ArrayList<DialogParam>()
                //D --> D
                //O --> O
                //N、H、A、B、C --> N、H、A、B、C
                for (it in this) {
                    var enableAdd = false
                    if(cueTransferActivityRepository.level.equals("D")){
                        if(it.title.equals("D")){
                            enableAdd = true
                        }
                    }
                    if(cueTransferActivityRepository.level.equals("O")){
                        if(it.title.equals("O")){
                            enableAdd = true
                        }
                    }
                    if(cueTransferActivityRepository.level.equals("N") || cueTransferActivityRepository.level.equals("H")||
                            cueTransferActivityRepository.level.equals("A")||cueTransferActivityRepository.level.equals("B")||
                            cueTransferActivityRepository.level.equals("C")){
                        if(it.title.equals("N")|| it.title.equals("H")|| it.title.equals("A")||it.title.equals("B")||it.title.equals("C")){
                            enableAdd = true
                        }
                    }
                    if(enableAdd) {
                        enableCustomerLevel.add(it)
                        var item = DialogParam(it.title, it.id.toString())
                        item.ikey = it.ikey
                        list.add(item)
                    }
                }

                var diolog = MyDialog.newInstance("客户级别", list)
                diolog.huidiaPosition = this@CueTransferActivityViewModel::myPoplevel
                diolog.show(content.supportFragmentManager, "missiles2")
            }
        }
    }

    val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    var maxDate = 0L

    /**
     * 选中移交回调
     */
    fun myPoplevel(position: Int) {
        customerlevelPosition = position
        if (customerlevelPosition != -1) {
            var item = enableCustomerLevel!![customerlevelPosition]!!
            customerlevelName.set(item.title)
            if(item.settings.alarmtime!="") {
                var times = simpleDateFormat.parse(item.settings.alarmtime)
                time.set(item.settings.alarmtime)
                maxDate = times.time
            }
        }
    }

    /**
     * 完成
     */
    fun clickBut(view: View) {
        if (userTypePosition == -1) {
            MyToast("请选择分配类型")
            return
        }
        if (memberPosition == -1) {
            if(userTypePosition == 0){
                MyToast("请选择分配用户")
            }else{
                MyToast("请选择分配经销商")
            }
            return
        }
//        if(userTypePosition == 0){
//            if (customerlevelPosition == -1) {
//                MyToast("请选择客户级别")
//                return
//            }
//            if (time.get().isNullOrBlank()) {
//                MyToast("请选择下次追踪时间")
//                return
//            }
//        }

        var salesid = ""
        var owneruid = ""

        if(userTypePosition == 0){
            owneruid = member?.get(memberPosition)?.uid.toString()
        }else{
            salesid = sales?.get(memberPosition)?.salesid
        }
        var customerid = ""
        if(userTypePosition == 0) {
            if(customerlevelPosition!=-1) {
                customerid = enableCustomerLevel?.get(customerlevelPosition)?.id.toString()
            }
        }
        var t = ""
        time.get()?.apply {
            t = this
        }
        var method: () -> Unit = {
            setData(view)
        }
        cueTransferActivityRepository.getHandover(userTypeId.value.toString(), salesid,owneruid, customerid, t, method)
    }

    /**
     * 成功回调
     */
    fun setData(view: View) {
        LiveEventBus.get().with("clueupdatge").postValue("")
        MyToast("分配成功")
        myFinish()
    }

    var year = ""
    var month = ""
    var day = ""
    var activity: AppCompatActivity? = null
    /**
     * 选择时间
     */
    fun timeText(view: View) {
        if(userTypePosition == 0){
            if (customerlevelPosition == -1) {
                MyToast("请先选择客户级别")
                return
            }
        }
        var content = view.context
        if (content is AppCompatActivity) {
            activity = content
            val datePickerFragment = DatePickerFragment()
            val c = Calendar.getInstance()
            datePickerFragment.minDate = c.timeInMillis
            datePickerFragment.maxDate = maxDate
            datePickerFragment.clickOk = this::onDateSet
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }


    /**
     * 点击日期回调
     */
    fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year = year.toString()
        this.month = month.toString()
        this.day = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onTimeSet
        timePickerFragment.show(activity?.supportFragmentManager!!, "timePicker")
    }

    /**
     * 点击时间回调
     */
    fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        var t = FunctionUtils.formatTime(year, month, day, hourOfDay, minute)
        time.set(t)
    }


}